package com.itheima.security.config;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.security.mapper.UserMapper;
import com.itheima.security.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

/**
 * @author 黑马程序员
 * @Company http://www.ithiema.com
 * @Version 1.0
 */
@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    UserMapper userMapper;

    /**
     * 根据用户名 加载 用户对象
     * @param username
     * @return 用户详情信息（从数据库查询出来的）
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println("用户名："+username);
        //1. 根据用户名从数据库查询用户信息
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, username);
        //数据库查询
        User user = userMapper.selectOne(wrapper);
        if(user != null){
            //2. 根据查询到用户信息， 封装 UserDetails 并返回
            org.springframework.security.core.userdetails.User userDetails =
                    new org.springframework.security.core.userdetails.User(
                            username,
                            user.getPassword(),
                            AuthorityUtils.commaSeparatedStringToAuthorityList(user.getRoles()));

            return userDetails;
        }


        return null;
    }
}
